package com.yadang.infra.service;

import com.yadang.infra.bean.XmlFieldConfig;
import com.yadang.infra.mapper.XmlFieldConfigMapper;
import com.yadang.infra.utils.XMLUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.LinkedList;
import java.util.List;

@Service
public class XmlFieldValidateService {

    @Autowired
    private XmlFieldConfigMapper xmlFieldConfigMapper;

    public List<String> validate(String xml) {
        List<String> resultList = new LinkedList<>();
        // 根据交易来源和交易类型查询对应的字段。查询那些字段是需要做非空校验的。
        String source = XMLUtils.getElementValueByXPath(xml, "/service/Body/source");
        String type = XMLUtils.getElementValueByXPath(xml, "/service/Body/type");

        XmlFieldConfig xmlFieldConfig = new XmlFieldConfig();
        xmlFieldConfig.setSource(source);
        xmlFieldConfig.setType(type);
        xmlFieldConfig.setIsRequired("1");

        List<XmlFieldConfig> list = xmlFieldConfigMapper.selectByBean(xmlFieldConfig);
        for (XmlFieldConfig fieldConfig : list) {
            // 查询出需要做非空校验的字段
            String fieldName = fieldConfig.getFieldName();
            String fieldValue = XMLUtils.getElementValueByXPath(xml, "/service/Body/" + fieldName);
            if (!StringUtils.hasText(fieldValue)) {
                resultList.add("["+fieldName+"]"+"不能为空");
            }

        }
        System.out.println(list);
        //
        return resultList;
    }
}
